package com.example.tuter.activity.util;

import android.os.Build;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.tuter.entity.Message;
import com.example.tuter.entity.PageResult;
import com.example.tuter.util.httpUtil.HttpCodeConstant;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PageResultHelper<T> {

    boolean isSlidingUpward = false;
    //滑动时的当前页面
    int NOW_PAGE = 1;
    //记录是否还有剩余
    Boolean isEnd = false;
    private ArrayList<T> data = new ArrayList<>();

    public ArrayList<T> getData() {
        return data;
    }

    public void add(T e) {
        data.add(e);
    }

    public void clear() {
        data.clear();
    }

    public T get(int position) {
        if (position < data.size())
            return data.get(position);
        return null;
    }

    public Integer size() {
        return data.size();
    }

    public void addAll(Collection<? extends T> c) {
        data.addAll(c);
    }

    public T getLast() {
        if (data.isEmpty()) return null;
        return data.get(data.size() - 1);
    }

    //获取到具体的函数后，将获得的结果放入指定的容器
    private void getPageResult(PageResultHandler<T> p, Call<Message<PageResult<T>>> call) {
        call.enqueue(new Callback<Message<PageResult<T>>>() {
            @Override
            public void onResponse(Call<Message<PageResult<T>>> call, Response<Message<PageResult<T>>> response) {
                Message<PageResult<T>> message = response.body();
                if (message.getCode() != HttpCodeConstant.NO_CONTENT.getValue()) {
                    //获取帖子后加入到容器中
                    List<T> cData = response.body().getData().getResult();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        data.addAll(cData);
                    }
                    //获得返回值后再更新ui
                    p.updateUI();
                } else {
                    isEnd = true;
                }

            }


            @Override
            public void onFailure(Call<Message<PageResult<T>>> call, Throwable t) {

            }
        });
    }

    public void reset() {
        this.NOW_PAGE = 1;
        this.isEnd = false;
        data.clear();
    }


    //添加分页功能
    public void addPageScroll(PageResultHandler<T> p, RecyclerView recyclerView) {
        //应该要先获取一下。
        getFirstPage(p);
        //添加滑动到底部的监听方式
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                // 当不滑动时
                if (!isEnd && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的itemPosition
                    int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
                    int itemCount = manager.getItemCount();
                    // 判断是否滑动到了最后一个item，并且是向上滑动
                    if (lastItemPosition == (itemCount - 1) && isSlidingUpward) {
                        //加载更多页数据
                        NOW_PAGE++;
                        Call<Message<PageResult<T>>> call = p.getDataByPage(NOW_PAGE);
                        getPageResult(p, call);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 大于0表示正在向上滑动，小于等于0表示停止或向下滑动
                isSlidingUpward = dy > 0;
            }
        });
    }

    //获取第一页数据
    public void getFirstPage(@NonNull PageResultHandler<T> p) {
        Call<Message<PageResult<T>>> call = p.getDataByPage(0);
        call.enqueue(new Callback<Message<PageResult<T>>>() {
            @Override
            public void onResponse(Call<Message<PageResult<T>>> call, Response<Message<PageResult<T>>> response) {
                Message<PageResult<T>> body = response.body();
                if (body != null && body.getCode() != HttpCodeConstant.NO_CONTENT.getValue()) {
                    assert response.body() != null;
                    if (body.getData().getTotal() == 1L) isEnd = true;
                    data.addAll(response.body().getData().getResult());
                    p.updateUI();
                } else {
                    isEnd = true;
                }
            }

            @Override
            public void onFailure(Call<Message<PageResult<T>>> call, Throwable t) {

            }
        });
    }

    public void getFirstPageInRefreshing(PageResultHandler<T> p, SwipeRefreshLayout swipeRefreshLayout, RecyclerView.Adapter adapter) {
        Call<Message<PageResult<T>>> call = p.getDataByPage(0);
        call.enqueue(new Callback<Message<PageResult<T>>>() {
            @Override
            public void onResponse(Call<Message<PageResult<T>>> call, Response<Message<PageResult<T>>> response) {
                if (response.code() == HttpCodeConstant.NO_CONTENT.getValue()) {
                    isEnd = true;
                    return;
                }
                int size = data.size();
                reset();
                adapter.notifyItemRangeRemoved(0, size);
                data.addAll(response.body().getData().getResult());
                swipeRefreshLayout.setRefreshing(false);
                p.updateUI();
            }

            @Override
            public void onFailure(Call<Message<PageResult<T>>> call, Throwable t) {

            }
        });
    }
    public void getFirstPageInRefreshing(PageResultHandler<T> p,RecyclerView.Adapter adapter) {
        Call<Message<PageResult<T>>> call = p.getDataByPage(0);
        call.enqueue(new Callback<Message<PageResult<T>>>() {
            @Override
            public void onResponse(Call<Message<PageResult<T>>> call, Response<Message<PageResult<T>>> response) {
                if (response.code() == HttpCodeConstant.NO_CONTENT.getValue()) {
                    isEnd = true;
                    return;
                }
                int size = data.size();
                reset();
                adapter.notifyItemRangeRemoved(0, size);
                data.addAll(response.body().getData().getResult());
                p.updateUI();
            }

            @Override
            public void onFailure(Call<Message<PageResult<T>>> call, Throwable t) {

            }
        });
    }


}
